package com.gxa.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxa.common.base.RespResult;
import com.gxa.common.base.RespResultCode;
import com.gxa.common.page.AccommodationQueryPage;
import com.gxa.common.utils.PageUtils;
import com.gxa.order.entity.AccommodationOrderItem;
import com.gxa.order.mapper.AccommodationMapper;
import com.gxa.order.service.AccommodationService;
import com.gxa.order.util.RedisUtils;
import com.gxa.order.util.dbfunction.DBFunctionAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class AccommodationServiceImpl extends ServiceImpl<AccommodationMapper, AccommodationOrderItem> implements AccommodationService {
    final AccommodationMapper accommodationMapper;
    final RedisTemplate redisTemplate;

    @Autowired
    public AccommodationServiceImpl(AccommodationMapper accommodationMapper, RedisTemplate redisTemplate) {
        this.accommodationMapper = accommodationMapper;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public RespResult listAccommodationByQueryPage(AccommodationQueryPage accommodationQueryPage) {
        RedisUtils<AccommodationOrderItem> redisUtils = new RedisUtils(redisTemplate);
        Integer start = PageUtils.getStart(accommodationQueryPage);
        accommodationQueryPage.setCurrentPage(start);
        String key = "accommodationOrderItems:"+ JSONObject.toJSONString(accommodationQueryPage) + accommodationQueryPage.getCurrentPage() +"_"+ accommodationQueryPage.getPageSize();
        List<AccommodationOrderItem> listFromRedis = redisUtils.getListFromRedis(key, AccommodationOrderItem.class, 1, TimeUnit.HOURS, new DBFunctionAdapter() {
            @Override
            public List<AccommodationOrderItem> getList() {
                return accommodationMapper.selectPageByQuery(accommodationQueryPage);
            }
        });
        RedisUtils<Integer> countRedisUtils = new RedisUtils(redisTemplate);
        String countKey = "accommodationOrderItemsCount:"+ JSONObject.toJSONString(accommodationQueryPage) + accommodationQueryPage.getCurrentPage() +"_"+ accommodationQueryPage.getPageSize();

        Integer count = countRedisUtils.getObjectFromRedis(countKey, Integer.class,1, TimeUnit.HOURS, new DBFunctionAdapter() {
            @Override
            public Integer getObject() {
                return accommodationMapper.selectCountByQuery(accommodationQueryPage);
            }
        });
        RespResult<HashMap> result = new RespResult<>(RespResultCode.OK);
        HashMap hashMap=new HashMap();
        hashMap.put("list",listFromRedis);
        hashMap.put("count",count);
        result.setData(hashMap);
        return result;
    }
}
